<html>
  <head></head>
  <body>
    <div>
      <p>history路由</p>
      <ul>
        <!-- 定义路由 -->
        <li><a href="/home">home</a></li>
        <li><a href="/about">about</a></li>

        <!-- 渲染路由对应的 UI -->
        <div id="routeView"></div>
      </ul>
    </div>
    <script>
      // 获取 routeView
      let routerView = document.getElementById('routeView')

      // 监听 popstate 事件
      window.addEventListener('popstate', () => {
        console.log('popstate-location', location)
        routerView.innerHTML = location.pathname
      })

      // 当初始的 HTML 文档被完全加载和解析完成之后，DOMContentLoaded 事件被触发
      window.addEventListener('DOMContentLoaded', () => {
        console.log('DOMContentLoaded-location', location)
        routerView.innerHTML = location.pathname

        // 拦截 a 标签，重写点击事件
        const linkList = document.querySelectorAll('a[href]')
        linkList.forEach(el =>
          el.addEventListener('click', function (e) {
            e.preventDefault()
            history.pushState(null, '', el.getAttribute('href'))
            routerView.innerHTML = location.pathname
          }),
        )
      })
    </script>
  </body>
</html>
